package com.safe.first.infrastructure.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.safe.first.infrastructure.context.BaseContextHandler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author Mickey
 * @since 2021/10/27
 */
@Slf4j
@AllArgsConstructor
public class ContextHandlerInterceptor extends HandlerInterceptorAdapter {

    private final ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            log.info("not exec!!! url={}", request.getRequestURL());
            return super.preHandle(request, response, handler);
        }

        String token = getHeader(request, "Authorization");
        if (Objects.isNull(token)) {
            return super.preHandle(request, response, handler);
        }
//        JWT jwt = JWTUtil.parseToken(token);
//        Object payload = jwt.getPayload(BaseContextConstants.JWT_KEY_USER_ID);

        BaseContextHandler.setUserId("dad");

        return super.preHandle(request, response, handler);
    }

    private String getHeader(HttpServletRequest request, String name) {
        String value = request.getHeader(name);
        if (StringUtils.isEmpty(value)) {
            return null;
        }
//        return StrHelper.decode(value);
        return value;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContextHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}
